package com.shaozj.auth.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.core.util.IdUtil;
import com.shaozj.auth.converter.AuthUserConverter;
import com.shaozj.auth.model.vo.UserAuthInfoVO;
import com.shaozj.captcha.config.properties.CaptchaProperties;
import com.shaozj.captcha.model.CaptchaResult;
import com.shaozj.captcha.service.CaptchaService;
import com.shaozj.core.constant.CacheConstants;
import com.shaozj.satoken.constant.SaTokenConstant;
import com.shaozj.satoken.model.UserAuthInfo;
import com.shaozj.auth.model.form.PasswordLoginForm;
import com.shaozj.auth.model.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
@Service
public class AuthService {

    private final CaptchaProperties captchaProperties;
    private final CaptchaService captchaService;
    private final StringRedisTemplate redisTemplate;
    private final AuthUserConverter authUserConverter;


    /**
     * 登录
     * @param loginForm
     * @return
     */
    public LoginVO login(PasswordLoginForm loginForm) {
        IAuthStrategy.login(loginForm, "password");


        return LoginVO.builder()
                .accessToken(StpUtil.getTokenValue())
                .expireIn(StpUtil.getTokenTimeout())
                .build();
    }

    /**
     * 退出登录
     */
    public void logout() {
        // 注意执行顺序，最后再执行logout
        // 清除缓存session
        StpUtil.getTokenSession().logout();
        // 退出登录
        StpUtil.logout();
    }

    /**
     * 获取验证码
     * @return
     */
    public CaptchaResult getCaptcha() {
        AbstractCaptcha captcha = captchaService.generate();
        //验证码文本缓存至Redis,用于登录校验
        String captchaId = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(CacheConstants.CAPTCHA_CODE_PREFIX + captchaId,
                captcha.getCode(),
                captchaProperties.getExpireSeconds(),
                TimeUnit.SECONDS);
        return CaptchaResult.builder()
                .captchaId(captchaId)
                .captchaBase64(captcha.getImageBase64())
                .build();
    }

    /**
     *  获取当前登录用户信息
     * @return
     */
    public UserAuthInfoVO getUserInfo() {
        log.error("=====sdfsdfsdfsdfsdfsdfsdfsdfs=={}", StpUtil.getTokenInfo());
        UserAuthInfo userInfo = (UserAuthInfo)StpUtil.getTokenSession().get(SaTokenConstant.USER_AUTH_INFO);
        return authUserConverter.info2VO(userInfo);
    }


    //TODO 获取用户路由


//
//    @Override
//    public boolean registerUser(UserRegisterForm registerForm) {
//        String mobile = registerForm.getMobile();
//        String code = registerForm.getCode();
//        // 校验验证码
//        String cacheCode = redisTemplate.opsForValue().get(RedisConstants.REGISTER_SMS_CODE_PREFIX + mobile);
//        Assert.isTrue(StrUtil.equals(code, cacheCode), "验证码不正确");
//        // 校验通过，删除验证码
//        redisTemplate.delete(RedisConstants.REGISTER_SMS_CODE_PREFIX + mobile);
//        // 校验手机号是否已注册
//        long count = count(new LambdaQueryWrapper<SysUser>()
//                .eq(SysUser::getMobile, mobile)
//                .or()
//                .eq(SysUser::getUsername, mobile)
//        );
//        Assert.isTrue(count == 0, "手机号已注册");
//        SysUser entity = new SysUser();
//        entity.setUsername(mobile);
//        entity.setMobile(mobile);
//        entity.setStatus(GlobalConstants.STATUS_YES);
//        // 设置默认加密密码
//        String defaultEncryptPwd = passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD);
//        entity.setPassword(defaultEncryptPwd);
//        // 新增用户，并直接返回结果
//        return save(entity);
//    }
}
